package com.yonyou.pmclouds.problemlog.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.assigninfo.entity.AssignInfoVO;
import com.yonyou.pmclouds.basecom.annotation.Insert;
import com.yonyou.pmclouds.basecom.entity.AdditionalPropertiesVOWrapper;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.service.CommonPropertiesProcessor;
import com.yonyou.pmclouds.copyperson.entity.CopyPersonVO;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.problemlog.entity.ProblemLogBillStatus;
import com.yonyou.pmclouds.problemlog.entity.ProblemLogVO;
import com.yonyou.pmclouds.problemlog.entity.ProblemLogViewVO;
import com.yonyou.pmclouds.problemlog.service.rmiitf.ProblemLogMaintain;
import com.yonyou.pmclouds.problemlog.service.rmiitf.ProblemLogQuery;
import com.yonyou.pmclouds.repairlog.entity.RepairLogVO;
import com.yonyou.pmclouds.user.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Slf4j
@Controller
@RequestMapping(value = "/mobile/problemlog")
public class ProblemLogController {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProblemLogMaintain maintain;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProblemLogQuery query;

    @Autowired
    private UserInfoQuery userQuery;
    @Autowired
    private CommonPropertiesProcessor propertiesProcessor;

    private static final String[] USER_ID_FIELDS = {ProblemLogVO.PK_RECTIFICATIONER,ProblemLogVO.CREATOR};
    private static final String[] USER_NAME_FIELDS = {ProblemLogVO.RECTIFICATIONER_NAME,ProblemLogVO.CREATOR_NAME};

    @RequestMapping(value = "/queryByProject")
    @ResponseBody
    public AdditionalPropertiesVOWrapper[] queryByProject(String pk_project) throws BusinessException {
        ProblemLogVO[] vos = query.qureyByProject(pk_project);
        if(vos == null || vos.length == 0) {
            return null;
        }
        setUserInfo(vos);
//        userQuery.tranUserInfoField(vos, USER_ID_FIELDS, USER_NAME_FIELDS);
        return propertiesProcessor.wrapAdditionalProps(vos);
    }
    
    @RequestMapping(value = "/queryOne")
    @ResponseBody
    public ProblemLogVO queryOne(String pk_problemlog) throws BusinessException {
        ProblemLogVO problemLogVO = query.queryOne(pk_problemlog);
        if(problemLogVO == null){
            return null;
        }
        setUserInfo(new ProblemLogVO[]{problemLogVO});
        return problemLogVO;
    }

    private void setUserInfo(ProblemLogVO[] problemLogVOS){
        if(problemLogVOS == null || problemLogVOS.length <= 0){
            return;
        }

        Set<String> userIdSet = new HashSet<>();

        for(ProblemLogVO logVO : problemLogVOS){
            // 交办人名称转换
            List<AssignInfoVO> assignVOList = logVO.getAssignVOList();
            if(assignVOList != null && assignVOList.size() > 0){
                for(AssignInfoVO assignVO : assignVOList){
                    userIdSet.add(assignVO.getAssignPerson());
                }
            }

            // 抄送人名称转换
            List<CopyPersonVO> copyPersonVOList = logVO.getCopyPersonVOS();
            if(copyPersonVOList != null && copyPersonVOList.size() > 0){
                for(CopyPersonVO copyPersonVO : copyPersonVOList){
                    userIdSet.add(copyPersonVO.getCopyPerson());
                }
            }

            // 整改人名称转换
            if(StringUtils.isNotEmpty(logVO.getPk_rectificationer())){
                userIdSet.add(logVO.getPk_rectificationer());
            }

            // 制单人名称转换
            if(StringUtils.isNotEmpty(logVO.getCreator())){
                userIdSet.add(logVO.getCreator());
            }

            // 修改人名称转换
            if(StringUtils.isNotEmpty(logVO.getModifier())){
                userIdSet.add(logVO.getModifier());
            }
        }

        if(userIdSet.size() <= 0){
            return;
        }

        Map<String, String> userInfoMap = new HashMap<>();
        UserInfo[] userInfoArray = userQuery.queryUsers(userIdSet.toArray(new String[]{}));
        if(userInfoArray == null || userInfoArray.length <= 0){
            return;
        }
        for(UserInfo userInfo : userInfoArray){
            userInfoMap.put(userInfo.getUserId(), userInfo.getUserName());
        }

        for(ProblemLogVO logVO : problemLogVOS){
            logVO.setRectificationer_name(userInfoMap.get(logVO.getPk_rectificationer()));
            logVO.setCreator_name(userInfoMap.get(logVO.getCreator()));
            logVO.setModifierName(userInfoMap.get(logVO.getModifierName()));

            List<AssignInfoVO> assignVOList = logVO.getAssignVOList();
            if(assignVOList != null && assignVOList.size() > 0){
                for(AssignInfoVO assignVO : assignVOList){
                    assignVO.setAssignPersonName(userInfoMap.get(assignVO.getAssignPerson()));
                }
            }

            List<CopyPersonVO> copyPersonVOList = logVO.getCopyPersonVOS();
            if(copyPersonVOList != null && copyPersonVOList.size() > 0){
                for(CopyPersonVO copyPersonVO : copyPersonVOList){
                    copyPersonVO.setCopyPersonName(userInfoMap.get(copyPersonVO.getCopyPerson()));
                }
            }
        }
    }

    @Insert
    @RequestMapping(value = "/add")
    @ResponseBody
    public ProblemLogVO add(@RequestBody ProblemLogVO vo) throws BusinessException {
        // 消息通知人名称转换
        vo.setCreator(RuntimeEnvironment.getLoginUserId());
        setUserInfo(new ProblemLogVO[]{vo});
        return maintain.add(vo);
    }

    @RequestMapping(value = "/assign")
    @ResponseBody
    public ProblemLogVO assign(@RequestBody ProblemLogVO vo) throws BusinessException {
        ProblemLogVO problemLogVO = queryOne(vo.getPk_problem());
        vo.setCopyPersonVOS(problemLogVO.getCopyPersonVOS());
        setUserInfo(new ProblemLogVO[]{vo});
        return maintain.updateAssignInfo(vo);
    }
    
    /**
     * 整改
     * @param vo
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/repair")
    @ResponseBody
    public ProblemLogVO repair(@RequestBody RepairLogVO vo) throws BusinessException {
        ProblemLogVO problemLogVO = queryOne(vo.getPk_problemlog());
        problemLogVO.setRepairlogs(new RepairLogVO[]{vo});
        maintain.repair(problemLogVO);
        return problemLogVO;
    }
    
    /**
     * 继续整改
     * @param vo
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "repairTo")
    @ResponseBody
    public ProblemLogVO repairTo(HttpServletResponse response,@RequestBody RepairLogVO vo) throws BusinessException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        ProblemLogVO problemLogVO = queryOne(vo.getPk_problemlog());
        problemLogVO.setRepairlogs(new RepairLogVO[]{vo});
        maintain.repairTo(problemLogVO);
        return problemLogVO;
    }
    /**
     * 通过
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "pass")
    @ResponseBody
    public ProblemLogVO pass(String pk_problemlog) throws BusinessException {
        ProblemLogVO problemLogVO = queryOne(pk_problemlog);
        maintain.pass(problemLogVO);
        return problemLogVO;
    }

    /**
     * 获取不同状态问题数
     *
     * @param pkProject
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/countProblemLog")
    @ResponseBody
    public ProblemLogViewVO countProblemLog(@RequestParam(value = "pkProject") String pkProject) throws BusinessException {
        if (StringUtils.isBlank(pkProject)) return null;
        ProblemLogVO[] problemLogVOS = query.qureyByProject(pkProject);
        if (problemLogVOS == null) return null;
        ProblemLogViewVO problemLogViewVO = new ProblemLogViewVO();
        int repairNum = 0, overTimeRepNum = 0, acceptingNum = 0;
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        for (ProblemLogVO vo : problemLogVOS) {
            if (vo.getBillstatus() == ProblemLogBillStatus.STATUS_REPAIRING) {
                repairNum++;
                if (vo.getEnddate() != null && vo.getEnddate().compareTo(cal.getTime()) < 0) {
                    overTimeRepNum++;
                }
            } else if (vo.getBillstatus() == ProblemLogBillStatus.STATUS_ACCEPTING) {
                acceptingNum++;
            }
        }
        problemLogViewVO.setRepairNum(repairNum);
        problemLogViewVO.setOverTimeRepNum(overTimeRepNum);
        problemLogViewVO.setAcceptingNum(acceptingNum);
        return problemLogViewVO;
    }

    /**
     * 查询不同状态问题列表
     *
     * @param pkProject
     * @param type
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/problemList")
    @ResponseBody
    public AdditionalPropertiesVOWrapper[] list(@RequestParam(value = "pkProject") String pkProject, @RequestParam(value = "type") Integer type) throws BusinessException {
        if (StringUtils.isBlank(pkProject)) return null;
        ProblemLogVO[] problemLogVOS = null;
        if (type == 0) {
            //待整改问题列表
            problemLogVOS = query.queryProblemLog(pkProject, ProblemLogBillStatus.STATUS_REPAIRING);
        } else if (type == 1) {
            //待验收问题列表
            problemLogVOS = query.queryProblemLog(pkProject, ProblemLogBillStatus.STATUS_ACCEPTING);
        } else if (type == 2) {
            //已关闭
            problemLogVOS = query.queryProblemLog(pkProject, ProblemLogBillStatus.STATUS_END);
        }
        userQuery.tranUserInfoField(problemLogVOS, USER_ID_FIELDS, USER_NAME_FIELDS);
        return propertiesProcessor.wrapAdditionalProps(problemLogVOS);
    }
}
